const Router = require('koa-router');
const tool = require("../../tools/tool");
const router = new Router();
const {db, Op, QueryTypes} = require("../../models/db");


// 终端未收票据
router.post('/bill/getUnReceiptList', async ctx => {
    try {
        let user = ctx.user
        let body = ctx.request.body
        let tenantId = user.tenantId;
        // let uid = user.id;
        let roleId = user.roleId;
        let roleName = user.roleName;
        if (!roleName) {
            return ctx.err('还没有设置用户的角色');
        }
        if (!roleId) {
            return ctx.err('还没有设置用户的角色');
        }
        let billNo = body.billNo
        let billDate = body.billDate;
        let billType = tool.xe.toString(body.billType);
        let buId = body.buId;
        if (!buId) {
            return ctx.err("请选择往来单位");
        }
        let sql = ` with bills as (
            select distinct a.id,a.tenantId, 
                   a.billDate,
                   a.billType,
                   a.billNo,
                   a.transType,
                   a.transTypeName,
                   arrearsReal arrears,
                   (nowCheck+yhAmount) hxAmount,arrearsReal-(nowCheck+yhAmount) leftAmount,a.remark
            from v_main_withhx a
            where a.tenantId=${tenantId} and a.buId=${buId} and a.billState='accounted' 
        ) select * from bills where tenantId=${tenantId} `
        if (billDate) {
            sql += ` and billDate<='${billDate}' `
        }
        if (billType === 'RECEIPT') {
            sql += ` and billType in('SALE','YS') `
        }
        if (billType === 'PAYMENT') {
            sql += ` and billType in('PUR','YF') `
        }
        if (billNo) {
            sql += ` and billNo like '%${billNo}%' `
        }
        sql += ' and isnull(leftAmount,0)<>0 order by billDate asc '
        let list = await db.query(sql, { type: QueryTypes.SELECT })

        for (let i = 0; i < list.length; i++) {
            if (!tool.xe.toNumber(list[i].arrears)) list[i].arrears = ''
            if (!tool.xe.toNumber(list[i].hxAmount)) list[i].hxAmount = ''
            if (!tool.xe.toNumber(list[i].leftAmount)) list[i].leftAmount = ''
        }
        return ctx.suc('', list)

    } catch (e) {
        return ctx.err(e);
    }
})
module.exports = router;